<template>
	<div :class="classNames">
		<template v-if="mode === 'STYLE2'">
			<div :class="`${baseClass}__content`"></div>
		</template>
		<template v-else>
			<div
				:class="`${baseClass}__header`"
				v-show="!(mode === 'STYLE3' && data.length >= 1)"
			>
				<span class="repeater-caption" v-if="showCaption && caption">
					{{ caption }}
				</span>
				<AppButton
					type="primary"
					class="repeater-add"
					size="small"
					shape="round"
					@click="add"
				>
					<template #icon>
						<van-icon name="plus" />
					</template>
				</AppButton>
			</div>
			<div :class="`${baseClass}__content`">
				<template v-for="(item, vIndex) of data">
					<van-swipe-cell :stop-propagation="true">
						<AppRow :class="`${baseClass}__item`" :layoutOpts="layoutOpts">
							<slot
								:data="item"
								:context="context"
								:index="[...parentIndex, vIndex]"
								:detailModel="childrenDetailModel[vIndex]"
								:viewParams="viewParams"
								:handleComponentAction="(controller: any, actionParam: IParam) => handleComponentAction(controller, actionParam, vIndex)"
							></slot>
						</AppRow>
						<template #right>
							<van-button
								square
								type="danger"
								text="删除"
								@click="remove(vIndex)"
							/>
						</template>
					</van-swipe-cell>
				</template>
			</div>
		</template>
	</div>
</template>
<script lang="ts" setup>
import { IContext, IEvent, IParam, ILayoutOpts } from '@/core';
import { AppRow } from '@/components/common/row';
import { AppButton } from '@components/common/button';
import { formMDCtrlRepeaterProps } from '../form';
type eventType =
	| 'componentInit'
	| 'valueChange'
	| 'mdCtrlUpdate'
	| 'mdCtrlAdd'
	| 'mdCtrlRemove';
interface Props {
	caption: string;
	context: IContext;
	viewParams: IParam;
	name: string;
	parentData: IParam;
	level?: number;
	mode?: 'DEFAULT' | 'STYLE2' | 'STYLE3';
	showCaption?: boolean;
	children?: IParam;
	columnAlign?: 'center' | 'left' | 'right';
	layoutOpts: ILayoutOpts;
}
const props = defineProps(formMDCtrlRepeaterProps);
const emit = defineEmits<{
	(name: 'component-action', value: IEvent<eventType>): void;
}>();
let childAbility: IParam;
//  基础类名
const baseClass = 'app-form-mdctrl-repeater';

const classNames = computed(() => {
	return {
		[baseClass]: true,
		[`${baseClass}--${props.name.toLowerCase()}`]: true,
		[`${baseClass}--${props.mode.toLowerCase()}`]: true,
		[`${baseClass}--level-${props.level}`]: true,
	};
});
const slotKeys = computed<string[]>(() => {
	return Object.keys(useSlots()) || [];
});

const data = ref<IParam[]>([]);

watch(
	() => props.parentData,
	() => {
		const { parentData, name } = props;
		if (parentData && name && parentData[name] && parentData[name].length > 0) {
			data.value = parentData[name];
		}
	},
	{ deep: true, immediate: true }
);

const executeFormDetail = ({ name, action, data: value }: IEvent<string>) => {
	switch (action) {
		case 'load':
			handleUpdate(props.name, { index: props.parentIndex, data: data.value });
			valueChange();
			break;
		case 'add':
			add();
			break;
		case 'remove':
			remove(value);
			break;
	}
	if (
		childAbility &&
		childAbility.executeFormDetail &&
		childAbility.executeFormDetail instanceof Function
	) {
		childAbility.executeFormDetail(name, action, value);
	}
};

const add = () => {
	const item: IParam = {};
	handleAdd(props.name, { index: props.parentIndex, data: item });
	data.value.push(item);
	valueChange();
};

const remove = (index: number) => {
	data.value.splice(index, 1);
	handleRemove(props.name, { index: props.parentIndex, data: index });
	valueChange();
};

const init = () => {
	emit('component-action', {
		name: props.name,
		action: 'componentInit',
		data: { executeFormDetail },
	});
};

const handleComponentAction = (
	controller: any,
	actionParam: IParam,
	vIndex: number
) => {
	const { action, data, name } = actionParam;
	switch (action) {
		case 'valueChange':
			handleChildValueChange(name, data, vIndex);
			break;
		case 'handleAdd':
			handleAdd(name, data);
		case 'mdCtrlUpdate':
			handleUpdate(name, data);
			break;
		case 'handleRemove':
			handleRemove(name, data);
			break;
		case 'componentInit':
			handleChildInit(name, data);
			break;
	}
};

const valueChange = () => {
	emit('component-action', {
		name: props.name,
		action: 'valueChange',
		data: data.value,
	});
};

const handleChildValueChange = (name: string, value: any, vIndex: number) => {
	if (!name) {
		return;
	}
	data.value[vIndex][name] = value;
	emit('component-action', {
		name: name,
		action: 'valueChange',
		data: value,
	});
	valueChange();
};

const handleAdd = (name: string, item: IParam) => {
    emit('component-action', {
		name: name,
		action: 'mdCtrlAdd',
		data: item,
	});
}

const handleRemove = (name: string, item: IParam) => {
    emit('component-action', {
		name: name,
		action: 'mdCtrlRemove',
		data: item,
	});
}

const handleUpdate = (name: string, item: IParam) => {
    emit('component-action', {
        name: name,
        action: 'mdCtrlUpdate',
        data: item,
    });
}
const handleChildInit = (name: string, ability: IParam) => {
    childAbility = ability;
}
init();
</script>
